'use strict'
// ---------------------MOVIE------------------------
var Movie = require('../models/movie');
var Comment = require('../models/comment');
var Category = require('../models/category');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');

// page
exports.detail = function (req, res) {

  var id = req.params.id;

  Movie.update({
    '_id': id
  }, {
    $inc: {
      pv: 1
    }
  }, function (err) {
    if (err) {
      console.log(err.message);
    }
  });

  Movie.findById(id, function (err, movie) {
    Comment
      .find({
        movie: id
      })
      .populate('from', 'name') // from id -> (ref)user.name
      .populate('reply.from reply.to', 'name')
      .exec(function (err, comments) {
        if (err) {
          console.log(err.code, err.message);
        }
        Category.findById(movie.category, function (err, category) {
          if (err) {
            console.log(err.code, err.message);
          }

          res.render('detail', {
            'title': '详情页',
            'movie': movie,
            'comments': comments,
            'category': category || ''
          });
        });
      });
  });
};

exports.new = function (req, res) {
  Category.find({}, function (err, categories) {
    if (err) {
      console.log(err);
    }
    res.render('admin', {
      title: '后台录入页',
      categories: categories,
      movie: {
        _id: ''
      }
    });
  });

};

exports.update = function (req, res) {
  var id = req.params.id;
  if (id) {
    Movie.findById(id, function (err, movie) {
      Category.find({}, function (err, categories) {
        res.render('admin', {
          title: '编辑页面',
          movie: movie,
          categories: categories
        });
      });
    });
  }
};
exports.list = function (req, res) {
  Movie.fetch(function (err, movies) {
    if (err) {
      console.log(err);
    }
    res.render('list', {
      title: '列表页',
      movies: movies
    });
  });
};
// action
exports.save = function (req, res) {
  var id = req.body.movie._id;
  var movieObj = req.body.movie;
  var _movie = new Movie(movieObj);
  var newCategoryName = movieObj.categoryName;
  var categoryId = _movie.category;

  // 如果使用本地海报地址
  // 需要改写为本地连接
  if (req.poster) {
    movieObj.poster = req.poster;
  }

  if (id !== undefined) { // UPDATE 编辑已有电影
    Movie.findById(id, function (err, movie) {
      if (err) {
        console.log(err);
      }
      // lodash函数库的_extend()方法 覆盖已有对象
      _movie = _.extend(movie, movieObj);
      _movie.save(function (err, movie) {
        if (err) {
          console.log(err.code, err.message);
          res.redirect('/');
        }
        if (newCategoryName.trim() !== '') { // ---------------自定义分类
          // --- 找到旧分类 - 删除旧分类保存的电影id
          Category.findOne({
            _id: movieObj.category
          }, function (err, oldCat) {
            if (err) {
              console.log(err);
            }
            if (oldCat) {
              _.remove(oldCat.movies, function (n) {
                console.log(n.toString(), id.toString());
                return n.toString() === id.toString();
              });
              Category.update({
                _id: movieObj.category
              }, {
                $set: {
                  movies: oldCat.movies
                }
              }, function (err) {
                if (err) {
                  console.log(err);
                }
              });
            }
          });
          Category.findOne({
            name: newCategoryName
          }, function (err, category) {
            if (category) { // 已有分类
              category.movies.push(movie._id); // 添加新分类
              category.save(function (err, category) {
                if (err) {
                  console.log(err.code, err.message);
                }
                movie.category = category._id;
                movie.save(function (err, movie) {
                  if (err) {
                    console.log(err.code, err.message);
                  }
                  res.redirect('/movie/' + movie._id);
                });
              });
            } else { // 新分类
              category = new Category({
                name: newCategoryName,
                movies: [movie._id]
              });
              category.save(function (err, category) {
                if (err) {
                  console.log(err.code, err.message);
                }
                movie.category = category._id;
                movie.save(function (err) {
                  if (err) {
                    console.log(err.code, err.message);
                  }
                  res.redirect('/movie/' + movie._id);
                });
              });
            }
          });
        } else if (categoryId) { // ---------------------分类选择单选卡
          // --- 找到旧分类 - 删除旧分类保存的电影id
          Category.findOne({
            _id: movieObj.category
          }, function (err, oldCat) {
            if (err) {
              console.log(err);
            }
            if (oldCat) {
              _.remove(oldCat.movies, function (n) {
                console.log(n.toString() === id.toString());
                return n.toString() === id.toString();
              });
              Category.update({
                _id: movieObj.category
              }, {
                $set: {
                  movies: oldCat.movies
                }
              }, function (err) {
                if (err) {
                  console.log(err);
                }
              });
            }
          });
          Category.findById(categoryId, function (err, category) {
            category.movies.push(movie._id); // - push 到新分类
            category.save(function (err) {
              if (err) {
                console.log(err.code, err.message);
              }
              res.redirect('/movie/' + movie._id);
            });
          });
        } else { // ----------------------都没有选择
          Category.findOne({
            name: '未分类'
          }, function (err, category) {
            if (category) {
              category.movies.push(movie._id);
              category.save(function (err, category) {
                if (err) {
                  console.log(err.code, err.message);
                }
                movie.category = category._id;
                movie.save(function (err, movie) {
                  if (err) {
                    console.log(err.code, err.message);
                  }
                  res.redirect('/movie/' + movie._id);
                });
              });
            } else {
              category = new Category({
                name: '未分类',
                movies: [movie._id]
              });
              category.save(function (err, category) {
                if (err) {
                  console.log(err.code, err.message);
                }
                movie.category = category._id;
                movie.save(function (err) {
                  if (err) {
                    console.log(err.code, err.message);
                  }
                  res.redirect('/movie/' + movie._id);
                });
              });
            }
          });
        }
      });
    });
  } else { // NEW 新增电影信息
    // save movie
    _movie.save(function (err, movie) {
      if (err) {
        console.log(err);
      }
      if (newCategoryName.trim() !== '') { // 自定义分类
        Category.findOne({
          name: newCategoryName
        }, function (err, category) {
          if (category) { // 已有分类
            category.movies.push(movie._id);
            category.save(function (err, category) {
              if (err) {
                console.log(err.code, err.message);
              }
              movie.category = category._id;
              movie.save(function (err, movie) {
                if (err) {
                  console.log(err.code, err.message);
                }
                res.redirect('/movie/' + movie._id);
              });
            });
          } else { // 新分类
            category = new Category({
              name: newCategoryName,
              movies: [movie._id]
            });
            category.save(function (err, category) {
              if (err) {
                console.log(err.code, err.message);
              }
              movie.category = category._id;
              movie.save(function (err) {
                if (err) {
                  console.log(err.code, err.message);
                }
                res.redirect('/movie/' + movie._id);
              });
            });
          }
        });
      } else if (categoryId) { // 分类选择单选卡
        Category.findById(categoryId, function (err, category) {
          category.movies.push(movie._id);
          category.save(function (err) {
            if (err) {
              console.log(err.code, err.message);
            }
            res.redirect('/movie/' + movie._id);
          });
        });
      } else { // 都没有选择
        Category.findOne({
          name: '未分类'
        }, function (err, category) {
          if (category) {
            category.movies.push(movie._id);
            category.save(function (err, category) {
              if (err) {
                console.log(err.code, err.message);
              }
              movie.category = category._id;
              movie.save(function (err, movie) {
                if (err) {
                  console.log(err.code, err.message);
                }
                res.redirect('/movie/' + movie._id);
              });
            });
          } else {
            category = new Category({
              name: '未分类',
              movies: [movie._id]
            });
            category.save(function (err, category) {
              if (err) {
                console.log(err.code, err.message);
              }
              movie.category = category._id;
              movie.save(function (err) {
                if (err) {
                  console.log(err.code, err.message);
                }
                res.redirect('/movie/' + movie._id);
              });
            });
          }
        });
      }
    });
  }
};
exports.del = function (req, res) {
  var id = req.query.id;

  if (id) {
    Movie.remove({
      '_id': id
    }, function (err) {
      if (err) {
        console.log(err);
      } else {
        res.json({
          success: 1
        });
      }
    });
  }
};

// midware - 保存上传的海报 - 建议以后改成异步
exports.savePoster = function (req, res, next) {
  var posterData = req.files.uploadPoster;
  var filePath = posterData.path; // 上传路径
  var originalFilename = posterData.originalFilename; // 原始文件名
  if (originalFilename) {
    fs.readFile(filePath, function (err, data) {
      var timestamp = Date.now();
      var type = posterData.type.split('/')[1];
      var poster = timestamp + '.' + type;
      var savePath = path.join(__dirname, '../../', '/public/upload/') + poster;

      // 保存到upload文件夹下
      fs.writeFile(savePath, data, function (err) {
        if (err) {
          console.log(err);
        }
        // 将海报的本地地址发送给下一个save流程
        req.poster = '/upload/' + poster;
        next();
      });
    });
  } else { // 没有选择上传
    next();
  }
};
